package io.adminboot.quartz.config;

import io.adminboot.quartz.entity.QuartzEntity;
import io.adminboot.quartz.service.IQuartzService;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

/**
 * 初始化TASK
 */
@Component
public class TaskRunner implements ApplicationRunner {

    private final static Logger LOGGER = LoggerFactory.getLogger(TaskRunner.class);

    @Autowired
    private IQuartzService jobService;
    @Autowired
    @Qualifier("Scheduler")
    private Scheduler scheduler;

    @Override
    public void run(ApplicationArguments var) throws Exception {
        Long count = jobService.count();
        if (count == 0) {
            LOGGER.info("初始化测试任务");
            QuartzEntity quartz = new QuartzEntity();
            quartz.setJobName("testJob01");
            quartz.setJobGroup("testGroup");
            quartz.setDescription("测试任务");
            quartz.setJobClassName("io.adminboot.quartz.job.ChickenJob");
            quartz.setCronExpression("0/20 * * * * ?");
            Class cls = Class.forName(quartz.getJobClassName());
            cls.newInstance();
            //构建job信息
            JobDetail job = JobBuilder.newJob(cls).withIdentity(quartz.getJobName(),
                    quartz.getJobGroup())
                    .withDescription(quartz.getDescription()).build();
            // 触发时间点
            CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(quartz.getCronExpression());
            Trigger trigger = TriggerBuilder.newTrigger().withIdentity("trigger" + quartz.getJobName(), quartz.getJobGroup())
                    .startNow().withSchedule(cronScheduleBuilder).build();
            //交由Scheduler安排触发
            scheduler.scheduleJob(job, trigger);
        }
    }

}